import { takeEvery, put, fork, delay, take, cancel, takeLatest } from 'redux-saga/effects'
import { actionTypes, increase, decrease } from '../action/counter'

function* asyncDecrease() {
    yield delay(2000)
    yield put(decrease())
}

function* asyncIncrease() {
    yield delay(2000)
    yield put(increase())
}

let task
function* autoIncrease() {
    while (true) {
        yield take(actionTypes.autoIncrease)
        if (task) {
            yield cancel(task)
        }
        task = yield fork(function* () {
            while (true) {
                yield delay(2000)
                yield put(increase())
            }
        })
    }
}

function* autoIncrease2() {
    while (true) {
        yield delay(2000)
        yield put(increase())
    }
}

function* stopAutoIncrease() {

}

function myTakeEvery(actionType, saga) {
    return fork(function* () {
        while (true) {
            yield take(actionType)
            fork(saga)
        }
    })
}


export default function* () {
    // yield takeEvery(actionTypes.asyncIncrease, asyncIncrease)
    // yield takeEvery(actionTypes.asyncDecrease, asyncDecrease)

    // const task = yield takeEvery(actionTypes.autoIncrease, autoIncrease)
    // yield takeEvery(actionTypes.stopAutoIncrease, stopAutoIncrease)


    yield fork(autoIncrease)
    // yield takeLatest(actionTypes.autoIncrease, autoIncrease2)
}